package entity

import (
	"errors"
	"fmt"
	"time"

	"shqsoft.cn/pas3ui/base"
	"shqsoft.cn/pas3ui/workflow"
	"shqsoft.cn/pas3ui/workflow/entity"

	"gorm.io/gorm"
)

//SpYhsq 用户申请
type SpYhsq struct {
	ID          int       `gorm:"column:ID;AUTO_INCREMENT;primary_key" json:"id"`
	SQSJ        time.Time `gorm:"column:SQSJ" json:"sqsj"`
	SYSUSERID   string    `gorm:"column:SysUserID" json:"sysuserid"`
	SYSUSERNAME string    `gorm:"column:SysUserName" json:"sysusername"`
	SQR         int       `gorm:"column:SQR" json:"sqr"`
	ORGANID     int       `gorm:"column:OrganID" json:"organid"`
	ORGANNAME   string    `gorm:"column:OrganName" json:"organname"`
	EMAIL       string    `gorm:"column:EMail" json:"email"`
	WFID        int       `gorm:"column:WFID" json:"wfid"`
	FRID        int       `gorm:"column:FRID" json:"frid"`
	Progress    float32   `gorm:"-" json:"progress"`
	StepName    string    `gorm:"-" json:"stepName"`
	Status      string    `gorm:"-" json:"status"`
	STEP        int       `gorm:"-" json:"step"`
}

//TableName SpYhsq表名
func (SpYhsq) TableName() string {
	return "T_SP_YHSQ"
}

//BeforeSave 保存前的触发器
func (s *SpYhsq) BeforeSave(tx *gorm.DB) (err error) {
	var count int
	row := tx.Raw(`select count("ID") from "T_SysUser" where "SysUserID"=?`, s.SYSUSERID).Row()
	err = row.Scan(&count)
	if err != nil {
		return
	}
	if count > 0 {
		return fmt.Errorf("工号:%s已经存在，不能申请！", s.SYSUSERID)
	}
	var frids []int
	err = tx.Table("T_SP_YHSQ").Where(`"SysUserID"=?`, s.SYSUSERID).Pluck("FRID", &frids).Error
	if err != nil {
		return
	}
	row = tx.Raw(`select count("ID") from "T_FLOW_RUN" where "ID" in (?) and "STATE" in ('0','1')`, frids).Row()
	err = row.Scan(&count)
	if err != nil {
		return
	}
	if count > 0 {
		return fmt.Errorf("工号:%s已经申请过了，请不要重复申请！", s.SYSUSERID)
	}
	row = tx.Raw(`select "OrganName" from "T_Organization" where "ID"=?`, s.ORGANID).Row()
	if s.ID == 0 {
		s.SQSJ = time.Now()
	}
	err = row.Scan(&s.ORGANNAME)
	if err != nil {
		return
	}
	if s.FRID == 0 {
		ei, _ := workflow.GetEntityInfo("SpYhsq")
		s.WFID, err = ei.WfidFunc(s)
		if err != nil {
			return err
		}
		if s.WFID == 0 {
			return errors.New("获取用户申请WFID失败")
		}
		runid, err := workflow.Create(s.WFID, s.SQR, tx)
		if err != nil {
			return err
		}
		s.FRID = runid
	}
	return
}

func (s *SpYhsq) AfterDelete(tx *gorm.DB) (err error) {
	if s.FRID > 0 {
		return workflow.Delete(s.FRID)
	}
	return nil
}

// AfterFind 查询后触发器
func (s *SpYhsq) AfterFind(tx *gorm.DB) (err error) {
	if s.FRID == 0 {
		s.Status = "exception"
		s.StepName = "校验错误"
		return
	}
	run := entity.FlowRun{}
	if err = tx.Find(&run, s.FRID).Error; err != nil {
		tx.Rollback()
		return
	}
	wf := workflow.GetWorkFlow(run.WFID)
	if wf == nil {
		return fmt.Errorf("指定的流程ID:%d在流程配置中不存在！", run.WFID)
	}
	act := wf.GetAction(run.Step)
	if act == nil {
		return fmt.Errorf("指定的stepID:%d在流程%s配置中不存在！", run.Step, wf.Name)
	}
	count := len(wf.Actions)
	s.STEP = run.Step
	s.StepName = act.Desc
	s.Progress = float32(act.Step*100) / float32(count)
	if s.Progress >= 100 && run.State == "0" {
		s.Progress = 95
	}
	s.Status = ""
	if run.State == "0" {
		s.Status = "active"
	} else if run.State == "2" {
		s.Status = "exception"
	} else {
		s.Status = "success"
	}
	return
}

//SpYhsqEF 获取实体类对象
func SpYhsqEF() base.EntityFunc {
	return func() interface{} {
		entity := SpYhsq{}
		return &entity
	}
}

//SpYhsqESF 获取实体类对象数组
func SpYhsqESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []SpYhsq
		return &entities
	}
}
func init() {
	dao := base.NewDefaultDao(SpYhsqEF(), SpYhsqESF(), nil, "my")
	filter := base.WorkFolowFilter{
		FilterColName: "FRID",
	}
	filter.SetDB("my")
	ei, err := workflow.GetEntityInfo("SpYhsq")
	if err != nil {
		panic(err)
	}
	filter.SetAdditional("wfid", ei.WfidsToString())
	filter.SetAdditional("manager", ei.MgMapToString())
	dao.Fileter = &filter
	base.DaoPoolObj.Put("SpYhsq", dao)
}
